<template>
    <div class="carousel-container swiper-container">
        <div class="carousel-wrapper swiper-wrapper">
            <img class="swiper-slide" v-for="(image, index) in images" :key="index" :src="image.img"
                alt="carousel-image">
        </div>
        <div class="swiper-pagination"></div>
    </div>
</template>

<script>
import Swiper, { Autoplay, Pagination } from 'swiper' // 明确导入需要的模块
import 'swiper/css'        // 核心基础样式
import 'swiper/css/pagination'  // 分页器样式

export default {
    props: ["images", "newColor"],
    data() {
        return {
            currentIndex: 0,
            swiper: null
        };
    },
    mounted() {
        this.currentIndex = this.images.findIndex(item => item.color == this.newColor);
        this.swiper = new Swiper('.carousel-container', {
            modules: [Autoplay, Pagination], // 添加模块启用
            // 自动播放
            autoplay: {
                delay: 3000,
                disableOnInteraction: false
            },
            on: {
                slideChange: (swiper) => {
                    this.currentIndex = swiper.activeIndex
                },
                realIndexChange: (swiper) => {
                    this.currentIndex = swiper.realIndex
                }
            },
            // 自由滑动
            freeMode: true,
            // 自动对齐
            freeModeSticky: true,
            // 分页器
            pagination: {
                el: '.swiper-pagination',
                clickable: true
            }
        });
    },
    watch: {
        currentIndex(newVal) {
            // console.log('index发生变化',newVal)
            this.$emit('play', newVal);
            if (this.swiper) {
                this.swiper.slideTo(newVal);
            }
        }
    },
    beforeDestroy() {
        if (this.swiper) {
            this.swiper.destroy();
        }
    }
};
</script>

<style scoped>
.carousel-container {
    position: relative;
    width: 94.6667vw;
    height: 32.5333vw;
    overflow: hidden;
    margin: 0 auto;
    border-radius: 2.6667vw;
}


.carousel-wrapper img {
    width: 94.6667vw;
    height: 32.5333vw;
    object-fit: cover;
}

/* 添加分页器位置样式 */
:deep(.swiper-pagination){
    position: absolute;
    bottom: 2.6667vw !important;
    left: -32vw !important;
    /* 调整位置 */
}

/* 分页点颜色 */
:deep(.swiper-pagination-bullet) {
    background: rgba(0,0,0, 0.5) !important;
}

:deep(.swiper-pagination-bullet-active){
    background: rgba(0, 0, 0, 0.6) !important;
}

</style>